/**
 * <p>Copyright:Copyright(c) 2019</p>
 * <p>Company:Professional</p>
 * <p>Package:org.cesgroup.course.util</p>
 * <p>File:WordConverter.java</p>
 * <p>类更新历史信息</p>
 *
 * @todo chanlong(陈龙) 创建于 Sep 12, 2019 10:16:50 AM
 */
package org.cesgroup.course.converter;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.cesgroup.course.enumeration.FileType;
import org.cesgroup.course.interceptor.Interceptor;
import org.cesgroup.course.interceptor.Invocation;
import org.cesgroup.course.interceptor.annon.Intercepts;
import org.cesgroup.course.interceptor.annon.Signature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

/**
 * <p>描述: </p>
 * <p>Company: Professional</p>
 *
 * @author chanlong(陈龙)
 * @version 1.0.2019
 * @date Sep 12, 2019 10:16:50 AM
 */
@Order(1)
@Component
@Intercepts({@Signature(type = Converter.class, method = "process", args = {Object.class, List.class})})
public class WordDocConverter implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        List arg = (List) args[1];
        if (arg.contains(FileType.doc.name()) && arg.size() == 1) {
            return process((byte[]) args[0]);
        }
        boolean remove = arg.remove(FileType.doc.name());
        Converter converter = (Converter) invocation.getTarget();
        Object process = converter.process(args[0], (List) args[1]);
        /**
         * 重新执行 转换操作，相当于后置处理
         */
        if (remove) {
            File file = new File((String) process);
            byte[] bytes = FileUtil.readBytes(file);
            return process(bytes);
        } else {
            return process;
        }
    }

    private Object process(final byte[] data) throws Throwable {
        String staticpath = locations + "/static/";
        String tmpdir = System.getProperty("java.io.tmpdir");
        String destdir = FileUtil.mkdir(staticpath + "/html/").getPath();
        String imgsdir = FileUtil.mkdir(destdir + "/image/").getPath();

        File folder = new File(tmpdir);
        File tempfile = FileUtil.createTempFile(folder);
        File datafile = FileUtil.writeBytes(data, tempfile);
        File htmlfile = FileUtil.newFile(destdir + "/" + RandomUtil.randomString(6) + ".html");
        System.out.println("=========WORD转HTML=============");
        
        HWPFDocument hwpf = new HWPFDocument(new FileInputStream(datafile));
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        WordToHtmlConverter converter = new WordToHtmlConverter(document);
        converter.setPicturesManager((content, type, name, width, height) -> {
            try (FileOutputStream out = new FileOutputStream(imgsdir + "/" + name)) {
                out.write(content);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "image/" + name;
        });
        converter.processDocument(hwpf);
        Document html = converter.getDocument();
        DOMSource dom = new DOMSource(html);
        StreamResult result = new StreamResult(htmlfile);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "html");
        transformer.transform(dom, result);
        return htmlfile.getPath();
    }

    @Value("${ces.resources.static-location}")
    private String locations;

    String getLocations() {
        return locations;
    }

    void setLocations(String locations) {
        this.locations = locations;
    }

}
